class MessageManager {
    constructor() {
        this.messages = new Map(); // conversationId -> messages[]
        this.currentConversationId = null;
        this.unreadCounts = new Map();
    }
    
    // 添加消息到指定会话
    addMessage(conversationId, messageData) {
        if (!this.messages.has(conversationId)) {
            this.messages.set(conversationId, []);
        }
        
        const messages = this.messages.get(conversationId);
        messages.push({
            ...messageData,
            id: messageData.messageId || this.generateMessageId(),
            timestamp: messageData.timestamp || Date.now(),
            status: 'sent'
        });
        
        // 按时间排序
        messages.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        
        // 保存到本地存储
        this.saveToLocalStorage(conversationId);
        
        return messages;
    }
    
    // 撤回消息
    recallMessage(conversationId, messageId, recalledBy) {
        const messages = this.messages.get(conversationId);
        if (!messages) return false;
        
        const messageIndex = messages.findIndex(msg => msg.id === messageId);
        if (messageIndex === -1) return false;
        
        // 检查撤回权限和时间限制（2分钟内）
        const message = messages[messageIndex];
        const timeDiff = Date.now() - new Date(message.timestamp).getTime();
        const RECALL_TIME_LIMIT = 2 * 60 * 1000; // 2分钟
        
        if (timeDiff > RECALL_TIME_LIMIT) {
            this.showNotification('消息已超过2分钟，无法撤回', 'error');
            return false;
        }
        
        // 标记消息为已撤回
        messages[messageIndex] = {
            ...message,
            isRecalled: true,
            recalledBy: recalledBy,
            recalledAt: new Date().toISOString(),
            originalContent: message.content,
            content: '该消息已被撤回'
        };
        
        this.saveToLocalStorage(conversationId);
        this.notifyMessageUpdate(conversationId, messages[messageIndex]);
        
        return true;
    }
    
    // 获取会话消息
    getMessages(conversationId, page = 1, pageSize = 20) {
        const messages = this.messages.get(conversationId) || [];
        const startIndex = Math.max(0, messages.length - page * pageSize);
        const endIndex = messages.length;
        
        return messages.slice(startIndex, endIndex);
    }
    
    // 生成唯一消息ID
    generateMessageId() {
        return 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    // 本地存储管理
    saveToLocalStorage(conversationId) {
        const key = `chat_messages_${conversationId}`;
        const messages = this.messages.get(conversationId) || [];
        localStorage.setItem(key, JSON.stringify(messages));
    }
    
    loadFromLocalStorage(conversationId) {
        const key = `chat_messages_${conversationId}`;
        const data = localStorage.getItem(key);
        if (data) {
            this.messages.set(conversationId, JSON.parse(data));
        }
    }
}